package com.yzt.zhuju.config;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yzt.zhuju.RXingUtils;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.main.SysConfigEvent;
import com.yzt.zhuju.manager.DomainManager;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.sysConfig.AppTextMapBean;
import com.yzt.zhuju.network.entity.sysConfig.CountryBean;
import com.yzt.zhuju.network.entity.sysConfig.SystemConfigBean;
import com.yzt.zhuju.network.entity.sysConfig.SystemConfigHideBean;
import com.yzt.zhuju.network.entity.user.UserLoginInfo;
import com.yzt.zhuju.constants.PreferenceConstant;
import com.yzt.p_base.utils.AppInfoUtils;
import com.yzt.p_base.utils.SharedPreferenceUtil;
import com.yzt.plugin_imageloader.ImageLoadUtil;

import java.util.List;

/**
 * author : bob
 * date   : 2022/11/29
 * desc   :
 */
public class AppConfigCacheManager {

    private final String TAG = "AppConfigCacheManager";

    private Context context;

    private final String mDeviceId = "";

    public boolean isLoginOut = false;

    //缓存系统设置
    private SystemConfigBean systemConfig;

    private JSONObject systemConfigNew;

    //提示文案
    private AppTextMapBean appTextMap;

    private static AppConfigCacheManager mInstance;

    //主页tab
    public final static String HIDE_TYPE_MAIN_MENU = "main_menu";

    /**
     * 获取系统配置错误数量通知
     */
    public int countSysConfigError;

    private final Handler handlerSysConfig = new Handler();

    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
    }

    public static AppConfigCacheManager getInstance() {
        if (mInstance == null) {
            mInstance = new AppConfigCacheManager();
        }
        return mInstance;
    }

    public void init() {
        init(null, null);
    }

    public void init(DataCallBackEvent<SystemConfigBean> systemConfigEvent, DataCallBackEvent<List<SystemConfigHideBean>> viewConfig) {
        if (RXingUtils.getLoginAccount() != null && RXingUtils.getLoginAccount().getUserInfo() != null) {
            UserLoginInfo loginAccount = RXingUtils.getLoginAccount();
            loginAccount.setEvent("");
            RXingUtils.saveLoginAccount(loginAccount);
        }
        //getViewConfig(viewConfig);
        getSysConfig(systemConfigEvent);
        loadAppSysConfig();
        getAppTextConfig();
        getNationalList();
        getLanguageList();
        DomainManager.getInstance().init(false);
    }

    /**
     * 获取国家列表
     */
    public void getNationalList() {
        BizLayer.getInstance().getSystemModule().getNationalList(new AresSubscriber<List<CountryBean>>() {
            @Override
            protected void onSuccess(List<CountryBean> map) {
                Log.e(TAG, JSONObject.toJSONString(map));
                SharedPreferenceUtil.getInstance().putValue(PreferenceConstant.SYSTEM_NATIONAL_LIST, JSONObject.toJSONString(map));
            }
        });
    }

    /**
     * 获取语言列表
     */
    public void getLanguageList() {
        BizLayer.getInstance().getSystemModule().getLanguageList(new AresSubscriber<List<CountryBean>>() {
            @Override
            protected void onSuccess(List<CountryBean> map) {
                Log.e(TAG, JSONObject.toJSONString(map));
                SharedPreferenceUtil.getInstance().putValue(PreferenceConstant.SYSTEM_LANGUAGE_LIST, JSONObject.toJSONString(map));
            }
        });
    }

    /**
     * 获取系统配置
     */
    public void getAppTextConfig() {
//        BizLayer.getInstance().getSystemModule().getAppTextConfig(new AresSubscriber<AppTextMapBean>() {
//            @Override
//            protected void onSuccess(AppTextMapBean map) {
//                AppConfigCacheManager.getInstance().setAppTextMap(map);
//            }
//        });
    }

    public AppTextMapBean getAppTextMap() {
        if (appTextMap == null) {
            appTextMap = new AppTextMapBean();
            getAppTextConfig();
        }
        return appTextMap;
    }

    /**
     * 获取配置
     */
    public String getViewConfig(String hideType) {
        return SharedPreferenceUtil.getInstance().getValue(hideType, "");
    }

    /**
     * 获取系统配置
     */
    public SystemConfigBean getSystemConfig() {
        if (systemConfig == null) {
            String value = SharedPreferenceUtil.getInstance().getValue(PreferenceConstant.SYSTEM_CONFIG_ENTITY, "");
            if (TextUtils.isEmpty(value)) {
                systemConfig = new SystemConfigBean();
                getSysConfig();
            } else {
                try {
                    systemConfig = JSON.parseObject(value, SystemConfigBean.class);
                } catch (Exception e) {
                    getSysConfig();
                    systemConfig = new SystemConfigBean();
                }
            }
        }
        return systemConfig;
    }

    /**
     * 获取系统配置
     */
    public void getSysConfig() {
        BizLayer.getInstance().getSystemModule().getSysConfig(new AresSubscriber<SystemConfigBean>() {
            @Override
            protected void onSuccess(SystemConfigBean entity) {
                systemConfig = entity;
                SharedPreferenceUtil.getInstance().putValue(PreferenceConstant.SYSTEMCONFIGENTITY, JSONObject.toJSONString(entity));
                if (systemConfig.getStartPageAdv() != null && !TextUtils.isEmpty(systemConfig.getStartPageAdv().getPic())) {
                    ImageLoadUtil.loadIv(context, systemConfig.getStartPageAdv().getPic(), new ImageView(context));
                }

                RxBus.getDefault().post(new SysConfigEvent());
            }

            @Override
            protected void onError(int code, String info) {
                super.onError(code, info);
                countSysConfigError++;
                if (countSysConfigError < 6) {
                    handlerSysConfig.postDelayed(() -> getSysConfig(), 500);
                }
            }
        });
    }

    /**
     * 获取系统配置
     */
    private void getSysConfig(DataCallBackEvent<SystemConfigBean> systemConfigEvent) {
        BizLayer.getInstance().getSystemModule().getSysConfig(new AresSubscriber<SystemConfigBean>() {
            @Override
            protected void onSuccess(SystemConfigBean entity) {
                systemConfig = entity;
                SharedPreferenceUtil.getInstance().putValue(PreferenceConstant.SYSTEMCONFIGENTITY, JSONObject.toJSONString(entity));
                if (systemConfig.getStartPageAdv() != null && !TextUtils.isEmpty(systemConfig.getStartPageAdv().getPic())) {
                    ImageLoadUtil.loadIv(context, systemConfig.getStartPageAdv().getPic(), new ImageView(context));
                }
                if (systemConfigEvent != null) {
                    systemConfigEvent.over(entity);
                }
            }

            @Override
            protected void onError(int code, String info) {
                super.onError(code, info);
                if (systemConfigEvent != null) {
                    systemConfigEvent.error(new Throwable(info));
                }
                countSysConfigError++;
                if (countSysConfigError < 6) {
                    handlerSysConfig.postDelayed(() -> getSysConfig(), 500);
                }
            }
        });
    }

    private void loadAppSysConfig() {
        BizLayer.getInstance().getSystemModule().loadAppSysConfig(new AresSubscriber<JSONObject>() {
            @Override
            protected void onSuccess(JSONObject entity) {
                systemConfigNew = entity;
                SharedPreferenceUtil.getInstance().putValue(PreferenceConstant.LOAD_APP_SYS_CONFIG, JSONObject.toJSONString(entity));
            }

            @Override
            protected void onError(int code, String info) {
                super.onError(code, info);
            }
        });
    }

    public String getDeviceId() {
        return mDeviceId;
    }

    public boolean isNewVersion() {
        boolean haveVersion = false;
        SystemConfigBean systemConfig = AppConfigCacheManager.getInstance().getSystemConfig();
        if (systemConfig != null) {
            if (Long.parseLong(systemConfig.getVersionCode()) > AppInfoUtils.getAppVersionCode(context)) {
                haveVersion = true;
            }
        }

        return haveVersion;
    }

    public interface DataCallBackEvent<D> {

        void over(D data);

        void error(Throwable throwable);
    }
}
